package cn.innosmart.aq.view.fragment;

import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.tutk.p2p.ConnectionManager;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.Calendar;
import java.util.HashMap;

import cn.innosmart.aq.R;
import cn.innosmart.aq.bean.AquariumBean;
import cn.innosmart.aq.bean.RuleBean;
import cn.innosmart.aq.customize.CustomCheckBox;
import cn.innosmart.aq.customize.PrioritySetDialog;
import cn.innosmart.aq.util.SharedUtil;
import cn.innosmart.aq.view.activity.PushMessageSettingAcitivity;
import cn.innosmart.aq.view.activity.RuleActivity;
import cn.innosmart.aq.view.activity.SmsPushMessageActivity;
import cn.innosmart.aq.view.activity.TelPushMessageActivity;

/**
 * Created by Woody on 2015/4/3.
 */
public class RuleStep3Fragment extends Fragment {
    int[] priorityStrIds = new int[]{R.string.priority_ignore_simple, R.string.priority_normal_simple, R.string.priority_important_simple, R.string.priority_high_important_simple};
    private View view;
    private ImageView tvNameIcon;
    private EditText etRuleName;
    private CheckBox cbEnable;
    private RelativeLayout rlEveryday;
    private RelativeLayout rlDailyTime;
    private RelativeLayout rlStart;
    private TextView tvStart;
    private TextView tvStartTime;
    private ImageView ivEverydayStartTimeSetting;
    private RelativeLayout rlEnd;
    private TextView tvEnd;
    private TextView tvEndTime;
    private ImageView ivEverydayEndTimeSetting;
    private RelativeLayout rlWeeklyTime;
    private LinearLayout llWeekpicker;
    private CustomCheckBox week0;
    private CustomCheckBox week1;
    private CustomCheckBox week2;
    private CustomCheckBox week3;
    private CustomCheckBox week4;
    private CustomCheckBox week5;
    private CustomCheckBox week6;
    private RelativeLayout rlWeekStart;
    private TextView tvWeekStart;
    private TextView tvWeekStartTime;
    private ImageView ivWeeklyStartTimeSetting;
    private RelativeLayout rlWeekEnd;
    private TextView tvWeekEnd;
    private TextView tvWeekEndTime;
    private ImageView ivWeeklyEndTimeSetting;
    private CheckBox cbPushMessage;
    private RadioButton rbAlways;
    private RadioButton rbEveryday;
    private RadioButton rbWeek;
    private TextView tvPriority;
    private HashMap<Integer, JSONArray> timeLine;
    private RuleBean ruleBean;
    private StringBuilder weekBuilder;
    private AnimationSet mShowAnimation;
    private AnimationSet mHidenAnimation;
    //设置时间的对话框
    private View.OnClickListener mTimeSettingOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            String time = null;
            switch (v.getId()) {
                case R.id.iv_everyday_start_time_setting:
                    time = ruleBean.getStart();
                    break;
                case R.id.iv_everyday_end_time_setting:
                    time = ruleBean.getEnd();
                    break;
                case R.id.iv_weekly_start_time_setting:
                    time = ruleBean.getStart();
                    break;
                case R.id.iv_weekly_end_time_setting:
                    time = ruleBean.getEnd();
                    break;
            }
            int hour;
            int minute;
            if (TextUtils.isEmpty(time)) {
                Calendar c = Calendar.getInstance();
                c.setTimeInMillis(System.currentTimeMillis());
                hour = c.get(Calendar.HOUR_OF_DAY);
                minute = c.get(Calendar.MINUTE);
            } else {
                hour = Integer.parseInt(time.split(":")[0]);
                minute = Integer.parseInt(time.split(":")[1]);
            }
            //时间设置的对话框
            new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    String strHour = calculateTime(hourOfDay);
                    String strMinute = calculateTime(minute);
                    switch (v.getId()) {
                        case R.id.iv_everyday_start_time_setting:
                            //每天的Start设置
                            tvStartTime.setText(strHour + ":" + strMinute);
                            ruleBean.setStart(tvStartTime.getText().toString());
                            checkEveryDayTime();
                            String timeStart = ruleBean.getStart();
                            int viewHour = Integer.valueOf(timeStart.split(":")[0]);
                            int viewMinute = Integer.valueOf(timeStart.split(":")[1]);
                            for (int i = 0; i < 7; i++) {
                                JSONArray jsonArray = timeLine.get(i);
                                if (jsonArray != null) {
                                    try {
                                        jsonArray.put(0, i * 24 * 60 + viewHour * 60 + viewMinute);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                            break;
                        case R.id.iv_everyday_end_time_setting:
                            //每天的End设置
                            tvEndTime.setText(strHour + ":" + strMinute);
                            ruleBean.setEnd(tvEndTime.getText().toString());
                            checkEveryDayTime();
                            String timeEnd = ruleBean.getEnd();
                            int viewEndHour = Integer.valueOf(timeEnd.split(":")[0]);
                            int viewEndMinute = Integer.valueOf(timeEnd.split(":")[1]);
                            for (int i = 0; i < 7; i++) {
                                JSONArray jsonArray = timeLine.get(i);
                                if (jsonArray != null) {
                                    try {
                                        jsonArray.put(1, i * 24 * 60 + viewEndHour * 60 + viewEndMinute);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                            break;
                        case R.id.iv_weekly_start_time_setting:
                            //每周的Start设置
                            tvWeekStartTime.setText(strHour + ":" + strMinute);
                            ruleBean.setStart(tvWeekStartTime.getText().toString());
                            checkWeekTime();
                            String timeWeekStart = ruleBean.getStart();
                            int viewWeekStartHour = Integer.valueOf(timeWeekStart.split(":")[0]);
                            int viewWeekStartMinute = Integer.valueOf(timeWeekStart.split(":")[1]);
                            for (int i = 0; i < 7; i++) {
                                JSONArray jsonArray = timeLine.get(i);
                                if (jsonArray != null) {
                                    try {
                                        jsonArray.put(0, i * 24 * 60 + viewWeekStartHour * 60 + viewWeekStartMinute);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                            break;
                        case R.id.iv_weekly_end_time_setting:
                            //每天的End设置
                            tvWeekEndTime.setText(strHour + ":" + strMinute);
                            ruleBean.setEnd(tvWeekEndTime.getText().toString());
                            checkWeekTime();
                            String timeWeekEnd = ruleBean.getEnd();
                            int viewWeekEndHour = Integer.valueOf(timeWeekEnd.split(":")[0]);
                            int viewWeekEndMinute = Integer.valueOf(timeWeekEnd.split(":")[1]);
                            for (int i = 0; i < 7; i++) {
                                JSONArray jsonArray = timeLine.get(i);
                                if (jsonArray != null) {
                                    try {
                                        jsonArray.put(1, i * 24 * 60 + viewWeekEndHour * 60 + viewWeekEndMinute);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                            break;
                    }
                }
            }, hour, minute, true).show();
        }
    };

    public static RuleStep3Fragment newInstance(AquariumBean aquariumBean) {
        RuleStep3Fragment f = new RuleStep3Fragment();
        Bundle args = new Bundle();
        args.putParcelable("aquarium", aquariumBean);
        f.setArguments(args);
        return f;
    }

    /**
     * 初始化自定义控件
     *
     * @param view
     */
    private void assignViews(View view) {
        tvPriority = (TextView) view.findViewById(R.id.tv_priority);
        tvPriority.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPriorityWindow(tvPriority);
            }
        });
        tvNameIcon = (ImageView) view.findViewById(R.id.iv_name_icon);
        etRuleName = (EditText) view.findViewById(R.id.et_rule_name);
        cbEnable = (CheckBox) view.findViewById(R.id.cb_enable);
        rbAlways = (RadioButton) view.findViewById(R.id.rb_always);
        rlEveryday = (RelativeLayout) view.findViewById(R.id.rl_everyday);
        rbEveryday = (RadioButton) view.findViewById(R.id.rb_everyday);
        rlDailyTime = (RelativeLayout) view.findViewById(R.id.rl_daily_time);
        rlStart = (RelativeLayout) view.findViewById(R.id.rl_start);
        tvStart = (TextView) view.findViewById(R.id.tv_start);
        tvStartTime = (TextView) view.findViewById(R.id.tv_start_time);
        ivEverydayStartTimeSetting = (ImageView) view.findViewById(R.id.iv_everyday_start_time_setting);
        rlEnd = (RelativeLayout) view.findViewById(R.id.rl_end);
        tvEnd = (TextView) view.findViewById(R.id.tv_end);
        tvEndTime = (TextView) view.findViewById(R.id.tv_end_time);
        ivEverydayEndTimeSetting = (ImageView) view.findViewById(R.id.iv_everyday_end_time_setting);
        rbWeek = (RadioButton) view.findViewById(R.id.rb_week);
        rlWeeklyTime = (RelativeLayout) view.findViewById(R.id.rl_weekly_time);
        llWeekpicker = (LinearLayout) view.findViewById(R.id.ll_weekpicker);
        week0 = (CustomCheckBox) view.findViewById(R.id.week0);
        week1 = (CustomCheckBox) view.findViewById(R.id.week1);
        week2 = (CustomCheckBox) view.findViewById(R.id.week2);
        week3 = (CustomCheckBox) view.findViewById(R.id.week3);
        week4 = (CustomCheckBox) view.findViewById(R.id.week4);
        week5 = (CustomCheckBox) view.findViewById(R.id.week5);
        week6 = (CustomCheckBox) view.findViewById(R.id.week6);
        rlWeekStart = (RelativeLayout) view.findViewById(R.id.rl_week_start);
        tvWeekStart = (TextView) view.findViewById(R.id.tv_week_start);
        tvWeekStartTime = (TextView) view.findViewById(R.id.tv_week_start_time);
        ivWeeklyStartTimeSetting = (ImageView) view.findViewById(R.id.iv_weekly_start_time_setting);
        rlWeekEnd = (RelativeLayout) view.findViewById(R.id.rl_week_end);
        tvWeekEnd = (TextView) view.findViewById(R.id.tv_week_end);
        tvWeekEndTime = (TextView) view.findViewById(R.id.tv_week_end_time);
        ivWeeklyEndTimeSetting = (ImageView) view.findViewById(R.id.iv_weekly_end_time_setting);
        cbPushMessage = (CheckBox) view.findViewById(R.id.cb_push_message);
    }

    /**
     * 根据数据内容判断添加 或 修改（填充旧数据）
     */
    private void assignData() {
        String name = ruleBean.getTitle();
        if (name != null) {
            etRuleName.setText(name);
        }
        tvPriority.setText(priorityStrIds[ruleBean.pns_priority]);
        tvPriority.setTag(ruleBean.pns_priority);
        String pns = ruleBean.getPns();
        String ruleId = ruleBean.getId();
        if (pns == null) {
            cbPushMessage.setChecked(false);
        } else if (pns.equals("pns")) {
            cbPushMessage.setChecked(true);
        }
        if (ruleId == null) {
            cbPushMessage.setChecked(true);
        }
        int enable = ruleBean.getEnabled();
        if (enable == 1) {
            cbEnable.setChecked(true);
        } else if (enable == 0) {
            cbEnable.setChecked(false);
        }
        if (ruleId == null) {
            cbEnable.setChecked(true);
        }
        int repeat_type = ruleBean.getRepeat_type();
        timeLine = ruleBean.getTimeLine();
        if (ruleBean.getId() == null && timeLine == null) {
            ruleBean.setTimeLine(new HashMap<Integer, JSONArray>());
            timeLine = ruleBean.getTimeLine();
            for (int i = 0; i < 7; i++) {
                JSONArray jsonChild = new JSONArray();
                jsonChild.put(i * 24 * 60);
                jsonChild.put((i + 1) * 24 * 60);
                timeLine.put(i, jsonChild);
            }
        } else {
        }
        if (repeat_type == 0) {
            rbAlways.setChecked(true);
            ruleBean.setStart("00:00");
            ruleBean.setEnd("23:59");
            tvStartTime.setText(ruleBean.getStart());
            tvEndTime.setText(ruleBean.getEnd());

        } else if (repeat_type == 1) {
            rbEveryday.setChecked(true);
            rlDailyTime.setVisibility(View.VISIBLE);
            rlDailyTime.startAnimation(mShowAnimation);
            tvStartTime.setText(ruleBean.getStart());
            tvEndTime.setText(ruleBean.getEnd());

        } else if (repeat_type == 2) {
            rbWeek.setChecked(true);
            rlWeeklyTime.setVisibility(View.VISIBLE);
            rlWeeklyTime.startAnimation(mShowAnimation);
            tvWeekStartTime.setText(ruleBean.getStart());
            tvWeekEndTime.setText(ruleBean.getEnd());
        }
        for (int i = 0; i < 7; i++) {
            if (timeLine.get(i) != null) {
                switch (i) {
                    case 0:
                        week0.setChecked(true);
                        break;
                    case 1:
                        week1.setChecked(true);
                        break;
                    case 2:
                        week2.setChecked(true);
                        break;
                    case 3:
                        week3.setChecked(true);
                        break;
                    case 4:
                        week4.setChecked(true);
                        break;
                    case 5:
                        week5.setChecked(true);
                        break;
                    case 6:
                        week6.setChecked(true);
                        break;
                }
            }
        }
    }

    /**
     * 格式化时间数据
     *
     * @param value
     * @return
     */
    public String format(int value) { //一位数填0
        String tmpStr = String.valueOf(value);
        if (value < 10) {
            tmpStr = "0" + tmpStr;
        }
        return tmpStr;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_rule_step3, container, false);
        assignViews(view);
        initAnimation();
        initData();
        initEditTextListener();
        initCheckEnableListener();
        initTimerSettingListener();
        assignData();
        initDayCheckListener();
        return view;
    }

    //初始化Checkbox
    private void initCheckEnableListener() {
        cbEnable.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    ruleBean.setEnabled(1);
                    tvNameIcon.setImageResource(R.drawable.rule_on);
                } else {
                    ruleBean.setEnabled(0);
                    tvNameIcon.setImageResource(R.drawable.rule_off);
                }
            }
        });
        cbPushMessage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    ruleBean.setPns("pns");
                } else {
                    ruleBean.setPns(null);
                }
            }
        });
    }


    /**
     * 初始化动画
     */
    private void initAnimation() {
        mShowAnimation = new AnimationSet(true);
        TranslateAnimation mTranslateShowAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        mTranslateShowAction.setDuration(500);
        AlphaAnimation mAlphaShowAction = new AlphaAnimation(0, 1);
        mAlphaShowAction.setFillAfter(true);
        mAlphaShowAction.setDuration(300);
        mShowAnimation.addAnimation(mTranslateShowAction);
        mShowAnimation.addAnimation(mAlphaShowAction);
        //影藏动画
        mHidenAnimation = new AnimationSet(true);
        TranslateAnimation mTranslateHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
                0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                -1.0f);
        mTranslateHiddenAction.setDuration(500);
        AlphaAnimation mAlphaHiddenAction = new AlphaAnimation(1, 0);
        mAlphaHiddenAction.setFillAfter(true);
        mAlphaHiddenAction.setDuration(300);
        mHidenAnimation.addAnimation(mAlphaHiddenAction);
        mHidenAnimation.addAnimation(mTranslateHiddenAction);
        mHidenAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (!rbWeek.isChecked()) {
                    rlWeeklyTime.setVisibility(View.GONE);
                }
                if (!rbEveryday.isChecked()) {
                    rlDailyTime.setVisibility(View.GONE);
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    /**
     * 初始化一直 每天 每周的单选框监听
     */
    private void initDayCheckListener() {
        rbAlways.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (rbEveryday.isChecked()) {
                        ruleBean.setRepeat_type(0);
                        rlDailyTime.startAnimation(mHidenAnimation);
                    }
                    if (rbWeek.isChecked()) {
                        rlWeeklyTime.startAnimation(mHidenAnimation);
                    }
                    ruleBean.setStart("00:00");
                    ruleBean.setEnd("23:59");
                    for (int i = 0; i < 7; i++) {
                        JSONArray jsonChild = new JSONArray();
                        jsonChild.put(i * 24 * 60);
                        jsonChild.put((i + 1) * 24 * 60 - 1);
                        timeLine.put(i, jsonChild);
                    }
                }
            }
        });
//        cb_always.setOncheckListener(new CheckBox.OnCheckListener() {
//            @Override
//            public void onCheck(boolean b) {
//
//            }
//        });
        rbWeek.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    ruleBean.setRepeat_type(2);
                    rlWeeklyTime.setVisibility(View.VISIBLE);
                    rlWeeklyTime.startAnimation(mShowAnimation);
                    if (rbEveryday.isChecked()) {
                        rlDailyTime.startAnimation(mHidenAnimation);
                    }
                    if (null != ruleBean.getStart() && null != ruleBean.getEnd()) {
                        tvWeekStartTime.setText(ruleBean.getStart());
                        tvWeekEndTime.setText(ruleBean.getEnd());
                    } else {
                        ruleBean.setStart(tvWeekStartTime.getText().toString());
                        ruleBean.setEnd(tvWeekEndTime.getText().toString());
                    }
                    String timeStart = tvWeekStartTime.getText().toString().trim();
                    String timeEnd = tvWeekEndTime.getText().toString().trim();
                    int viewStarHour = Integer.valueOf(timeStart.split(":")[0]);
                    int viewStatMinute = Integer.valueOf(timeStart.split(":")[1]);
                    int viewEndHour = Integer.valueOf(timeEnd.split(":")[0]);
                    int viewEndMinute = Integer.valueOf(timeEnd.split(":")[1]);
                    if (week0.isChecked()) {
                        JSONArray jsonChild = new JSONArray();
                        jsonChild.put(viewStarHour * 60 + viewStatMinute);
                        jsonChild.put(viewEndHour * 60 + viewEndMinute);
                        timeLine.put(0, jsonChild);
                    } else {
                        timeLine.remove(0);
                    }
                    if (week1.isChecked()) {
                        JSONArray jsonChild = new JSONArray();
                        jsonChild.put(1 * 24 * 60 + viewStarHour * 60 + viewStatMinute);
                        jsonChild.put(1 * 24 * 60 + viewEndHour * 60 + viewEndMinute);
                        timeLine.put(1, jsonChild);
                    } else {
                        if (timeLine.get(1) != null)
                            timeLine.remove(1);
                    }
                    if (week2.isChecked()) {
                        JSONArray jsonChild = new JSONArray();
                        jsonChild.put(2 * 24 * 60 + viewStarHour * 60 + viewStatMinute);
                        jsonChild.put(2 * 24 * 60 + viewEndHour * 60 + viewEndMinute);
                        timeLine.put(2, jsonChild);
                    } else {
                        timeLine.remove(2);
                    }
                    if (week3.isChecked()) {
                        JSONArray jsonChild = new JSONArray();
                        jsonChild.put(3 * 24 * 60 + viewStarHour * 60 + viewStatMinute);
                        jsonChild.put(3 * 24 * 60 + viewEndHour * 60 + viewEndMinute);
                        timeLine.put(3, jsonChild);
                    } else {
                        timeLine.remove(3);
                    }
                    if (week4.isChecked()) {
                        JSONArray jsonChild = new JSONArray();
                        jsonChild.put(4 * 24 * 60 + viewStarHour * 60 + viewStatMinute);
                        jsonChild.put(4 * 24 * 60 + viewEndHour * 60 + viewEndMinute);
                        timeLine.put(4, jsonChild);
                    } else {
                        timeLine.remove(4);
                    }
                    if (week5.isChecked()) {
                        JSONArray jsonChild = new JSONArray();
                        jsonChild.put(5 * 24 * 60 + viewStarHour * 60 + viewStatMinute);
                        jsonChild.put(5 * 24 * 60 + viewEndHour * 60 + viewEndMinute);
                        timeLine.put(5, jsonChild);
                    } else {
                        timeLine.remove(5);
                    }
                    if (week6.isChecked()) {
                        JSONArray jsonChild = new JSONArray();
                        jsonChild.put(6 * 24 * 60 + viewStarHour * 60 + viewStatMinute);
                        jsonChild.put(6 * 24 * 60 + viewEndHour * 60 + viewEndMinute);
                        timeLine.put(6, jsonChild);
                    } else {
                        timeLine.remove(6);
                    }
                } else {
                    rlWeeklyTime.startAnimation(mHidenAnimation);
                    ruleBean.setWeekdays(0);
                }
            }
        });
//        cb_week.setOncheckListener(new CheckBox.OnCheckListener() {
//            @Override
//            public void onCheck(boolean b) {
//
//            }
//        });
        rbEveryday.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    ruleBean.setRepeat_type(1);
                    rlDailyTime.setVisibility(View.VISIBLE);
                    rlDailyTime.startAnimation(mShowAnimation);
                    if (rbWeek.isChecked()) {
                        rlWeeklyTime.startAnimation(mHidenAnimation);
                    }
                    if (null != ruleBean.getStart() && null != ruleBean.getEnd()) {
                        tvStartTime.setText(ruleBean.getStart());
                        tvEndTime.setText(ruleBean.getEnd());
                    } else {
                        ruleBean.setStart(tvStartTime.getText().toString());
                        ruleBean.setEnd(tvEndTime.getText().toString());
                    }
                    String timeStart = tvStartTime.getText().toString().trim();
                    String timeEnd = tvEndTime.getText().toString().trim();
                    int viewStarHour = Integer.valueOf(timeStart.split(":")[0]);
                    int viewStatMinute = Integer.valueOf(timeStart.split(":")[1]);
                    int viewEndHour = Integer.valueOf(timeEnd.split(":")[0]);
                    int viewEndMinute = Integer.valueOf(timeEnd.split(":")[1]);
                    for (int i = 0; i < 7; i++) {
                        JSONArray jsonChild = new JSONArray();
                        jsonChild.put(i * 24 * 60 + viewStarHour * 60 + viewStatMinute);
                        jsonChild.put(i * 24 * 60 + viewEndHour * 60 + viewEndMinute);
                        timeLine.put(i, jsonChild);
                    }
                } else {
                    rlDailyTime.startAnimation(mHidenAnimation);
                    ruleBean.setWeekdays(0);
                }
            }
        });
//        cb_everyday.setOncheckListener(new CheckBox.OnCheckListener() {
//            @Override
//            public void onCheck(boolean b) {
//
//
//            }
//        });
        //初始化周日的监听
        week0.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    JSONArray chileTimeLine = new JSONArray();
                    String start[] = tvWeekStartTime.getText().toString().trim().split(":");
                    String end[] = tvWeekEndTime.getText().toString().trim().split(":");
                    int startIndex = Integer.valueOf(start[0]) * 60 + Integer.valueOf(start[1]);
                    int endIndex = Integer.valueOf(end[0]) * 60 + Integer.valueOf(end[1]);
                    chileTimeLine.put(startIndex);
                    chileTimeLine.put(endIndex);
                    timeLine.put(0, chileTimeLine);
                } else {
                    timeLine.remove(0);
                }
            }
        });
        //初始化周一的监听
        week1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    JSONArray chileTimeLine = new JSONArray();
                    String start[] = tvWeekStartTime.getText().toString().trim().split(":");
                    String end[] = tvWeekEndTime.getText().toString().trim().split(":");
                    int startIndex = Integer.valueOf(start[0]) * 60 + Integer.valueOf(start[1]) + 1 * 24 * 60;
                    int endIndex = Integer.valueOf(end[0]) * 60 + Integer.valueOf(end[1]) + 1 * 24 * 60;
                    chileTimeLine.put(startIndex);
                    chileTimeLine.put(endIndex);
                    timeLine.put(1, chileTimeLine);
                } else {
                    timeLine.remove(1);
                }
            }
        });
        //初始化周二的监听
        week2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    JSONArray chileTimeLine = new JSONArray();
                    String start[] = tvWeekStartTime.getText().toString().trim().split(":");
                    String end[] = tvWeekEndTime.getText().toString().trim().split(":");
                    int startIndex = Integer.valueOf(start[0]) * 60 + Integer.valueOf(start[1]) + 2 * 24 * 60;
                    int endIndex = Integer.valueOf(end[0]) * 60 + Integer.valueOf(end[1]) + 2 * 24 * 60;
                    chileTimeLine.put(startIndex);
                    chileTimeLine.put(endIndex);
                    timeLine.put(2, chileTimeLine);
                } else {
                    timeLine.remove(2);
                }
            }
        });
        //初始化周三的监听
        week3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    JSONArray chileTimeLine = new JSONArray();
                    String start[] = tvWeekStartTime.getText().toString().trim().split(":");
                    String end[] = tvWeekEndTime.getText().toString().trim().split(":");
                    int startIndex = Integer.valueOf(start[0]) * 60 + Integer.valueOf(start[1]) + 3 * 24 * 60;
                    int endIndex = Integer.valueOf(end[0]) * 60 + Integer.valueOf(end[1]) + 3 * 24 * 60;
                    chileTimeLine.put(startIndex);
                    chileTimeLine.put(endIndex);
                    timeLine.put(3, chileTimeLine);
                } else {
                    timeLine.remove(3);
                }
            }
        });
        //初始化周四的监听
        week4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    JSONArray chileTimeLine = new JSONArray();
                    String start[] = tvWeekStartTime.getText().toString().trim().split(":");
                    String end[] = tvWeekEndTime.getText().toString().trim().split(":");
                    int startIndex = Integer.valueOf(start[0]) * 60 + Integer.valueOf(start[1]) + 4 * 24 * 60;
                    int endIndex = Integer.valueOf(end[0]) * 60 + Integer.valueOf(end[1]) + 4 * 24 * 60;
                    chileTimeLine.put(startIndex);
                    chileTimeLine.put(endIndex);
                    timeLine.put(4, chileTimeLine);
                } else {
                    timeLine.remove(4);
                }
            }
        });
        //初始化周五的监听
        week5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    JSONArray chileTimeLine = new JSONArray();
                    String start[] = tvWeekStartTime.getText().toString().trim().split(":");
                    String end[] = tvWeekEndTime.getText().toString().trim().split(":");
                    int startIndex = Integer.valueOf(start[0]) * 60 + Integer.valueOf(start[1]) + 5 * 24 * 60;
                    int endIndex = Integer.valueOf(end[0]) * 60 + Integer.valueOf(end[1]) + 5 * 24 * 60;
                    chileTimeLine.put(startIndex);
                    chileTimeLine.put(endIndex);
                    timeLine.put(5, chileTimeLine);
                } else {
                    timeLine.remove(5);
                }
            }
        });
        //初始化周六的监听
        week6.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    JSONArray chileTimeLine = new JSONArray();
                    String start[] = tvWeekStartTime.getText().toString().trim().split(":");
                    String end[] = tvWeekEndTime.getText().toString().trim().split(":");
                    int startIndex = Integer.valueOf(start[0]) * 60 + Integer.valueOf(start[1]) + 6 * 24 * 60;
                    int endIndex = Integer.valueOf(end[0]) * 60 + Integer.valueOf(end[1]) + 6 * 24 * 60;
                    chileTimeLine.put(startIndex);
                    chileTimeLine.put(endIndex);
                    timeLine.put(6, chileTimeLine);
                } else {
                    timeLine.remove(6);
                }
            }
        });
    }

    //0 unknown  1: ADD 2:Modify
    private void initData() {
        ruleBean = RuleActivity.ruleBean;
    }

    private void initEditTextListener() {
        etRuleName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                ruleBean.setTitle(etRuleName.getText().toString().trim());
            }
        });
    }

    private void initTimerSettingListener() {
        ivEverydayStartTimeSetting.setOnClickListener(mTimeSettingOnClickListener);
        ivEverydayEndTimeSetting.setOnClickListener(mTimeSettingOnClickListener);
        ivWeeklyStartTimeSetting.setOnClickListener(mTimeSettingOnClickListener);
        ivWeeklyEndTimeSetting.setOnClickListener(mTimeSettingOnClickListener);
    }

    /**
     * 计算时间，格式化
     *
     * @param time
     * @return
     */
    private String calculateTime(int time) {
        String strTime = String.valueOf(time);
        int length = strTime.length();
        if (length == 1) {
            strTime = "0" + time;
        }
        return strTime;
    }

    //**检查Start 和end是否规范
    private boolean checkEveryDayTime() {
        String startTime = tvStartTime.getText().toString();
        String[] timeStartArray = startTime.split(":");
        int startHour = Integer.valueOf(timeStartArray[0]);
        int startMinute = Integer.valueOf(timeStartArray[1]);
        String endTime = tvEndTime.getText().toString();
        String[] timeEndArray = endTime.split(":");
        int endHour = Integer.valueOf(timeEndArray[0]);
        int endMinute = Integer.valueOf(timeEndArray[1]);
        if (startHour > endHour) {
            Toast.makeText(getActivity(), getString(R.string.activity_rule_end_above_start), Toast.LENGTH_SHORT).show();
            return false;
        } else if (startHour == endHour) {
            if (startMinute < endMinute) {
                return true;
            } else {
                Toast.makeText(getActivity(), getString(R.string.activity_rule_end_above_start), Toast.LENGTH_SHORT).show();
                return false;
            }
        } else {
            return true;
        }
    }

    private void preSetDayEndTimeByDayStartTime(String strHour, String strMinute) {
        int hour = Integer.valueOf(strHour);
        int minute = Integer.valueOf(strMinute);
        if (minute == 59) {
            if (hour == 23) {
                minute = 58;
                tvStartTime.setText("23:58");
                tvEndTime.setText("23:59");
            } else {
                minute = 0;
                hour = hour + 1;
                tvEndTime.setText(calculateTime(hour) + ":" + calculateTime(minute));
            }
        } else {
            minute = minute + 1;
            tvEndTime.setText(calculateTime(hour) + ":" + calculateTime(minute));
        }
    }

    private void preSetWeekEndTimeByWeekStartTime(String strHour, String strMinute) {
        int hour = Integer.valueOf(strHour);
        int minute = Integer.valueOf(strMinute);
        if (minute == 59) {
            if (hour == 23) {
                minute = 58;
                tvWeekStartTime.setText("23:58");
                tvWeekEndTime.setText("23:59");
            } else {
                minute = 0;
                hour = hour + 1;
                tvWeekEndTime.setText(calculateTime(hour) + ":" + calculateTime(minute));
            }
        } else {
            minute = minute + 1;
            tvWeekEndTime.setText(calculateTime(hour) + ":" + calculateTime(minute));
        }
    }

    private String resetEveryDayEndTime() {
        String startTime = tvStartTime.getText().toString();
        String[] timeArray = startTime.split(":");
        int startHour = Integer.valueOf(timeArray[0]);
        int startMinute = Integer.valueOf(timeArray[1]);
        if (startMinute == 59) {
            if (startHour == 23) {
                tvStartTime.setText("23:58");
                return startHour + ":" + startMinute;
            } else {
                startHour = startHour + 1;
                startMinute = 0;
                return calculateTime(startHour) + ":" + "00";
            }
        } else {
            startMinute = startMinute + 1;
            return calculateTime(startHour) + ":" + calculateTime(startMinute);
        }
    }

    private String resetWeekEndTime() {
        String startTime = tvWeekStartTime.getText().toString();
        String[] timeArray = startTime.split(":");
        int startHour = Integer.valueOf(timeArray[0]);
        int startMinute = Integer.valueOf(timeArray[1]);
        if (startMinute == 59) {
            if (startHour == 23) {
                tvWeekStartTime.setText("23:58");
                return startHour + ":" + startMinute;
            } else {
                startHour = startHour + 1;
                startMinute = 0;
                return calculateTime(startHour) + ":" + "00";
            }
        } else {
            startMinute = startMinute + 1;
            return calculateTime(startHour) + ":" + calculateTime(startMinute);
        }
    }

    /**
     * 检查每周的时间是否规范
     *
     * @return
     */
    private boolean checkWeekTime() {
        String startTime = tvWeekStartTime.getText().toString();
        String[] timeStartArray = startTime.split(":");
        int startHour = Integer.valueOf(timeStartArray[0]);
        int startMinute = Integer.valueOf(timeStartArray[1]);
        String endTime = tvWeekEndTime.getText().toString();
        String[] timeEndArray = endTime.split(":");
        int endHour = Integer.valueOf(timeEndArray[0]);
        int endMinute = Integer.valueOf(timeEndArray[1]);
        if (startHour > endHour) {
            Toast.makeText(getActivity(), getString(R.string.activity_rule_end_above_start), Toast.LENGTH_SHORT).show();
            return false;
        } else if (startHour == endHour) {
            if (startMinute < endMinute) {
                return true;
            } else {
                Toast.makeText(getActivity(), getString(R.string.activity_rule_end_above_start), Toast.LENGTH_SHORT).show();
                return false;
            }
        } else {
            return true;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    //----
    //----
    //
    //----
    //----
    //显示优先级的对话框
    private void showPriorityWindow(final TextView tvPriority) {
        final PrioritySetDialog priorityDialog = new PrioritySetDialog(getActivity(), (Integer) tvPriority.getTag());
        priorityDialog.setTitle(getString(R.string.alarm_priority_title));
        priorityDialog.setNegativeButton(R.string.cancel, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                priorityDialog.dismiss();
            }
        });
        priorityDialog.setPositiveButton(R.string.sure, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                priorityDialog.checkChange();
            }
        });
        priorityDialog.setOnChangeListener(new PrioritySetDialog.OnChangeListener() {
            @Override
            public void onChange(int type) {
                switch (type) {
                    case 1:
                        if (checkPushStatus()) {
                            priorityDialog.dismiss();
                            tvPriority.setText(getString(priorityStrIds[type]));
                            tvPriority.setTag(type);
                            ruleBean.pns_priority = type;
                        } else {
                            //跳转到Push界面
                            switchToPushActivity();
                        }
                        break;
                    case 2:
//                        checkPushAndSmsStatus();
                        if (checkPushStatus()) {
                            if (checkSmsStatus()) {
                                priorityDialog.dismiss();
                                tvPriority.setText(getString(priorityStrIds[type]));
                                tvPriority.setTag(type);
                                ruleBean.pns_priority = type;
                            } else {
                                //跳转到SMS界面
                                switchToSmsActivity();
                            }
                        } else {
                            //跳转到Push界面
                            switchToPushActivity();
                        }
                        break;
                    case 3:
                        if (checkPushStatus()) {
                            if (checkTelStatus()) {
                                priorityDialog.dismiss();
                                tvPriority.setText(getString(priorityStrIds[type]));
                                tvPriority.setTag(type);
                                ruleBean.pns_priority = type;
                            } else {
                                //跳转到Tel界面
                                switchToTelActivity();
                            }
                        } else {
                            //跳转到Push界面
                            switchToPushActivity();
                        }
                        break;
                }
            }
        });
        priorityDialog.setCanceledOnTouchOutside(true);
        priorityDialog.show();
    }

    private void switchToTelActivity() {
        Intent intent = new Intent(getActivity(), TelPushMessageActivity.class);
        startActivityForResult(intent, 1);
        getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    private void switchToSmsActivity() {
        Intent intent = new Intent(getActivity(), SmsPushMessageActivity.class);
        startActivityForResult(intent, 1);
        getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    private void switchToPushActivity() {
        Intent intent = new Intent(getActivity(), PushMessageSettingAcitivity.class);
        startActivityForResult(intent, 1);
        getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    private boolean checkTelStatus() {
        if (SharedUtil.getInstance().readTelStatus(ConnectionManager.getInstance().getCurrentConnectionEntity().getUid())) {
            //关闭对话框
            return true;
        } else {
            //跳转到Push界面
            return false;
        }
    }

    private boolean checkSmsStatus() {
        if (SharedUtil.getInstance().readSmsStatus(ConnectionManager.getInstance().getCurrentConnectionEntity().getUid())) {
            //关闭对话框
            return true;
        } else {
            //跳转到Push界面
            return false;
        }
    }

    private boolean checkPushStatus() {
        if (SharedUtil.getInstance().readXinStatus(ConnectionManager.getInstance().getCurrentConnectionEntity().getUid())) {
            //关闭对话框
            return true;
        } else {
            //跳转到Push界面
            return false;
        }
    }
}
